package userclievt

import (
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/interactiond"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/ddd"
)

const (
	// EvTypeUser 用户相关事件
	EvTypeUser = "users"
)
const (
	// EvtActLookInfo 查看信息
	EvtActLookInfo = "lookinfo"
)

func AddEventListenerForLookInfoEvent(handler func(ctx ddd.Context, evt ddd.Event, uid string, targetTyp interactiond.IGTargetType, targetid string) error) {
	ddd.AddEventListener(EvTypeUser, EvtActLookInfo, ddd.CreEventListener(func(ctx ddd.Context, evt ddd.Event) error {

		uid, targetType, targetid := FromUserLookInfoEvt(evt)
		if handler != nil {
			return handler(ctx, evt, uid, targetType, targetid)
		}
		return nil
	}))
}

// TriggerLookInfoEvent 触发一个浏览事件
func TriggerLookInfoEvent(from, uid string, targettype interactiond.IGTargetType, targetid string) {
	ddd.TriggerForEvent(NewUserLookInfoEvent(from, uid, targettype, targetid))
}

// NewUserLookInfoEvent 创建用户浏览信息事件
func NewUserLookInfoEvent(from, uid string, targettype interactiond.IGTargetType, targetid string) ddd.Event {
	return ddd.Event{
		Type:   EvTypeUser,
		Action: EvtActLookInfo,
		Data: map[string]interface{}{
			"uid":         uid,
			"target_type": targettype,
			"target_id":   targetid,
		},
	}
}

// FromUserLookInfoEvt 解析用户浏览信息事件数据
func FromUserLookInfoEvt(evt ddd.Event) (uid string, targettype interactiond.IGTargetType, targetid string) {
	if evt.Data == nil {
		return
	}
	if tmp, ok := evt.Data.(map[string]interface{}); ok {
		if vt, ok := tmp["uid"]; ok {
			uid = vt.(string)
		}
		if vt, ok := tmp["target_type"]; ok {
			targettype = vt.(interactiond.IGTargetType)
		}
		if vt, ok := tmp["target_id"]; ok {
			targetid = vt.(string)
		}
	}
	return
}
